/*
 * Copyright (c) 2016 4PX Information Technology Co.,Ltd. All rights reserved.
 */
package com.open.spring.utils.soap.proxy;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

import org.springframework.ws.transport.WebServiceConnection;
import org.springframework.ws.transport.http.HttpTransportException;
import org.springframework.ws.transport.http.HttpUrlConnectionMessageSender;

/**
 * 设置翻墙代理
 * 
 * @author hcx
 * @date 2017年7月24日
 */
public class HttpUrlConnectionMessageSenderEx extends HttpUrlConnectionMessageSender {

    private Proxy proxy;

    private Map<String, String> headerMap;

    @Override
    public WebServiceConnection createConnection(URI uri) throws IOException {
        URL url = uri.toURL();
        URLConnection connection = null;
        if (null != proxy) {
            connection = url.openConnection(proxy);
        } else {
            connection = url.openConnection();
        }
        if (null != headerMap) {
            for (String key : headerMap.keySet()) {
                connection.setRequestProperty(key, headerMap.get(key));
            }
        }
        if (!(connection instanceof HttpURLConnection)) {
            throw new HttpTransportException("URI [" + uri + "] is not an HTTP URL");
        } else {
            HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
            prepareConnection(httpURLConnection);
            return new HttpUrlConnectionEx(httpURLConnection);
        }
    }

    /**
     * @return the proxy
     */
    public Proxy getProxy() {
        return proxy;
    }

    /**
     * @param proxy the proxy to set
     */
    public void setProxy(Proxy proxy) {
        this.proxy = proxy;
    }

    /**
     * @return the headerMap
     */
    public Map<String, String> getHeaderMap() {
        return headerMap;
    }

    /**
     * @param headerMap the headerMap to set
     */
    public void setHeaderMap(Map<String, String> headerMap) {
        this.headerMap = headerMap;
    }

}
